package com.ys.otms.services.impl;

import com.ys.otms.dao.IHuoYuanDao;
import com.ys.otms.dto.*;
import com.ys.otms.services.IHuoYuanServices;
import com.ys.otms.utils.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by Administrator on 2018/10/17.
 */
@Service
public class HuoYuanServiceImpl implements IHuoYuanServices {

    private static Logger logger = LoggerFactory.getLogger(HuoYuanServiceImpl.class);
    static Map<Integer,String> shipState = new HashMap<>();
    static {
        shipState.put(0,"在航（主机推)");
        shipState.put(1,"锚泊");
        shipState.put(2,"失控");
        shipState.put(3,"操纵受限");
        shipState.put(4,"吃水受限");
        shipState.put(5,"靠泊");
        shipState.put(6,"搁浅");
        shipState.put(7,"捕捞作业");
        shipState.put(8,"靠帆船提供动力");
        shipState.put(9,"为将来 HSC 航行状态修正保留");
        shipState.put(10,"为将来 WIG 航行状态修正保留");
    }

    @Autowired
    private IHuoYuanDao iHuoYuanDao;
    @Override
    /**
     * 新增货源
     */
    public JSONObject insertCompanyHuoYuan(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("HuoYuanServiceImpl insertCompanyHuoYuan start obj{}",obj);
        String zhDate = JsonUtil.getJSONObjectString(obj,"zhDate");
        String original = JsonUtil.getJSONObjectString(obj,"original");
        String destination = JsonUtil.getJSONObjectString(obj,"destination");
        String planTonnage = JsonUtil.getJSONObjectString(obj,"planTonnage");
        String goodsName = JsonUtil.getJSONObjectString(obj,"goodsName");
        String contactMan = JsonUtil.getJSONObjectString(obj,"contactMan");
        String contactPhone = JsonUtil.getJSONObjectString(obj,"contactPhone");
        String instructions =JsonUtil.getJSONObjectString(obj,"instrucselectShipFeedBacktions");
        String informShip = JsonUtil.getJSONObjectString(obj,"informShip");
        JSONArray jsonArray = JsonUtil.getJSONArray(obj,"shipIdList");
        HuoYuanDto huoYuanDto = new HuoYuanDto();
        JSONObject jsonObject = new JSONObject();
        if (jsonArray.size()==0 && jsonArray == null){
            jsonObject.put("SUCCESS",false);
            jsonObject.put("MSG","请选择船舶！");
        }else{
            if (StringUtil.isNotEmpty(zhDate)&&StringUtil.isNotEmpty(original)&&StringUtil.isNotEmpty(destination)&&StringUtil.isNotEmpty(planTonnage)&&
                    StringUtil.isNotEmpty(goodsName)&&StringUtil.isNotEmpty(contactMan)&&StringUtil.isNotEmpty(contactPhone)&&StringUtil.isNotEmpty(instructions)&&StringUtil.isNotEmpty(informShip)){
                huoYuanDto.setZhDate(zhDate);
                huoYuanDto.setOriginal(original);
                huoYuanDto.setDestination(destination);
                huoYuanDto.setPlanTonnage(planTonnage);
                huoYuanDto.setGoodsName(goodsName);
                huoYuanDto.setContactMan(contactMan);
                huoYuanDto.setContactPhone(contactPhone);
                huoYuanDto.setInstructions(instructions);
                huoYuanDto.setCompanyId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
                huoYuanDto.setUserId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_USER_ID")));
                huoYuanDto.setInformShip(Integer.parseInt(informShip));
                huoYuanDto.setCreateTime(new Timestamp((new Date()).getTime()));
                iHuoYuanDao.insertCompanyHuoYuan(huoYuanDto);
                List<HuoYuanShipDto> huoYuanShipDtoList = new ArrayList<>();
                for (int i=0;i<jsonArray.size();i++){
                    HuoYuanShipDto huoYuanShipDto = new HuoYuanShipDto();
                    huoYuanShipDto.setHuoYuanId(huoYuanDto.getId());
                    huoYuanShipDto.setShipId(Integer.parseInt(jsonArray.getJSONObject(i).getString("shipId")));
                    huoYuanShipDto.setState(0);
                    huoYuanShipDtoList.add(huoYuanShipDto);
                }
                iHuoYuanDao.insertHuoYuanShip(huoYuanShipDtoList);
                jsonObject.put("SUCCESS",true);
                jsonObject.put("MSG","新增成功！");
            }else{
                jsonObject.put("SUCCESS",false);
                jsonObject.put("MSG","所有信息不能为空！");
            }
        }
        return jsonObject;
    }

    @Override
    public JSONObject selectCompanyHuoYuan(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("HuoYuanServiceImpl selectCompanyHuoYuan start obj{}",obj);
        String page =JsonUtil.getJSONObjectString(obj,"page");
        String limit = JsonUtil.getJSONObjectString(obj,"limit");
        JSONObject jsonObject = new JSONObject();
        ParamDto paramDto = new ParamDto();
        PageUtil.setPage(Integer.parseInt(page),Integer.parseInt(limit),paramDto);
//        paramDto.setUserId(1);
        paramDto.setUserId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
        List<HuoYuanDto> huoYuanDtoList = iHuoYuanDao.selectCompanyHuoYuan(paramDto);
        int huoYuanCount = iHuoYuanDao.selectCompanyHuoYuanByCount(paramDto);
        int informShipCount = iHuoYuanDao.selectCompanyInformShipByCount(paramDto);
        if (huoYuanDtoList==null || huoYuanDtoList.size()==0){
            jsonObject.put("SUCCESS",false);
            jsonObject.put("MSG","查询数据为空！");
        }else{
            jsonObject.put("huoYuanDtoList",huoYuanDtoList);
            jsonObject.put("huoYuanCount",huoYuanCount);
            jsonObject.put("informShipCount",informShipCount);
        }
        return jsonObject;
    }


    @Override
    public JSONObject selectHuoYuanShip(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("HuoYuanServiceImpl selectHuoYuanShip start obj{}",obj);
        String huoyuanId = JsonUtil.getJSONObjectString(obj,"huoyuanId");
        String state = JsonUtil.getJSONObjectString(obj,"state");
        String page =JsonUtil.getJSONObjectString(obj,"page");
        String limit = JsonUtil.getJSONObjectString(obj,"limit");
        ParamDto paramDto = new ParamDto();
        PageUtil.setPage(Integer.parseInt(page),Integer.parseInt(limit),paramDto);
        if (StringUtil.isNotEmpty(huoyuanId)){
            paramDto.setHuoYuanId(Integer.parseInt(huoyuanId));
        }
        if (StringUtil.isNotEmpty(state)){
            paramDto.setState(Integer.parseInt(state));
        }
//        paramDto.setUserId(1);
        paramDto.setUserId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
        List<ShipInfoDto> shipInfoDtoList = iHuoYuanDao.selectHuoYuanShip(paramDto);
        int hyShipCount = iHuoYuanDao.selectHuoYuanShipByCount(paramDto);
        JSONObject jsonObject = new JSONObject();
        if(shipInfoDtoList ==null || shipInfoDtoList.size()==0){
            jsonObject.put("SUCCESS",false);
            jsonObject.put("MSG","查询数据为空！");
        }else {
            JSONArray areaArr = null;
            StringBuffer sb = new StringBuffer();
            for (ShipInfoDto shipInfoDto : shipInfoDtoList) {
                sb.append(shipInfoDto.getMmsi()).append(",");
            }
            if (sb.length() > 0) {
                JSONObject qryManyObj = new JSONObject();
                qryManyObj.put("shipIds", sb.substring(0,sb.length() - 1));
                JSONObject manyObj = ShipXyAPIUtil.getManyShip(qryManyObj);
                areaArr = manyObj.getJSONArray("data");
            }
            for (ShipInfoDto shipInfoDto : shipInfoDtoList){
                for (int i=0;i<areaArr.size();i++){
                    JSONObject areaObj = (JSONObject) areaArr.get(i);
                    if (shipInfoDto.getMmsi().equals(areaObj.getString("mmsi"))){
                        shipInfoDto.setArrivalTime(areaObj.getString("eta_std"));
                        shipInfoDto.setDestination(areaObj.getString("dest_std"));
                        shipInfoDto.setLat(areaObj.getString("lat"));
                        shipInfoDto.setLon(areaObj.getString("lon"));
                        shipInfoDto.setSailingState(shipState.get(areaObj.getInt("navistat")));
                    }
                }
            }
            jsonObject.put("shipsList",shipInfoDtoList);
            jsonObject.put("shipsCount",hyShipCount);
            jsonObject.put("SUCCESS",true);
        }
        return jsonObject;
    }

    /**
     * 立即联系查询电话号码
     * @param obj
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject selectHuoYuanShipByPhone(JSONObject obj) throws Exception {
        logger.info("HuoYuanServiceImpl selectHuoYuanShipByPhone start obj{}",obj);
        JSONArray jsonArray = JsonUtil.getJSONArray(obj,"shipList");
        JSONObject jsonObject = new JSONObject();
        List<ShipInfoDto> shipInfoDtoList = new ArrayList<>();
        if (jsonArray.size()>0){
            for (int i = 0; i <jsonArray.size() ; i++) {
                ShipInfoDto shipInfoDto = new ShipInfoDto();
                shipInfoDto.setShipId(Integer.parseInt(jsonArray.getJSONObject(i).getString("shipId")));
                shipInfoDtoList.add(shipInfoDto);
            }
            List<ShipInfoDto> shipInfoDtos = iHuoYuanDao.selectShipPhoneByListShipId(shipInfoDtoList);
            if (shipInfoDtos.size()>0){
                jsonObject.put("shipInfoDtos",shipInfoDtos);
                jsonObject.put("SUCCESS",true);
            }else{
                jsonObject.put("SUCCESS",false);
                jsonObject.put("MSG","没有该船舶信息！");
                return jsonObject;
            }
        }else{
            jsonObject.put("SUCCESS",false);
            jsonObject.put("MSG","请选择船舶！");
            return jsonObject;
        }
        jsonObject.put("SUCCESS",true);
        return jsonObject;
    }

}
